package test;

import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

/**
 * Created by Carman
 * <p>
 * Date: 2018/4/16 - 17:27
 * <p>
 * 描述:
 * WebSocket 客户端
 */
public class WebSocketClient extends WebSocketListener {

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        System.out.println("打开链接");
        // 打开链接
        webSocket.send("hello world");
        webSocket.send("welcome");
        webSocket.send(ByteString.decodeHex("adef"));
//        webSocket.close(1000, "再见");
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        System.out.println("onMessage: " + text);
    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        System.out.println("onMessage: " + bytes);
    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
//        webSocket.close(1000, null);
        // 关闭中
        System.out.println("onClosing: " + code + "/" + reason);
    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        System.out.println("onClosed: " + code + "/" + reason);
        // 链接关闭
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        System.out.println("onFailure: " + t.getMessage());
        // 链接失败
    }
}
